<?php

namespace App\Console\Commands\Wechat;

use Illuminate\Console\Command;
use Log;
use DB;
use Illuminate\Console\Scheduling\Schedule;

class Voice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'voice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'every 5 minute execute voice amr trant mav';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 执行转换脚本,将amr转换成mav,并更新语音的url地址、时长、大小
     *
     * @return mixed
     */
    public function handle(Schedule $schedule)
    {
        $convertUrl = "sh ".base_path('app/Common/Silk/converter.sh ');
        
        $msgs = DB::table('wechat_msg')->select('wechat_msg.id','attachment.url','attachment.fileName','wechat_msg.voice_attachment_id')
                               ->leftJoin('attachment','attachment.id','=','wechat_msg.voice_attachment_id')
                               ->where('wechat_msg.voice_attachment_id','>',0)
                               ->where('wechat_msg.voiceUrl','=','')
                               ->take(100)->get();
        
        foreach ($msgs as $msg) {
            $voiceUrl =  public_path($msg->url.$msg->fileName);
            //执行exec 将amr 转换成mav
            shell_exec("$convertUrl $voiceUrl wav");
            //获取转换后的语音的时长和大小
            $voiceFormat = json_decode(shell_exec("ffprobe -v quiet -print_format json -show_format ".str_replace('.amr', '.wav', $voiceUrl)));
            //更新附件库语音信息
            DB::table('attachment')->where('id',$msg->voice_attachment_id)->update(
                [
                    'long'=>round($voiceFormat->format->duration,2),
                    'fileName' => str_replace('.amr','.wav', $msg->fileName),
                    'fileSize' => $voiceFormat->format->size,
                    'fileType' => 'wav'
                ]
            );
            //更新消息表地址
            DB::table('wechat_msg')->where('id',$msg->id)->update(['voiceUrl'=>str_replace('.amr', '.wav', $msg->url.$msg->fileName)]);
        }
    }
}
